package 尚硅谷.juc.test11;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 资源类
 */
public class MyCache {

    /**
     * volatile：可见性，防止指令重排
     */
    private static volatile Map<String,Object> map=new HashMap<>();

    //实例化一个读写锁
    private static ReentrantReadWriteLock rrwl=new ReentrantReadWriteLock();
    //实例化读锁
    private static ReentrantReadWriteLock.ReadLock readLock=rrwl.readLock();
    //实例化写锁
    private static ReentrantReadWriteLock.WriteLock writeLock=rrwl.writeLock();

    /**
     * 写操作必须保证原子性：同一时间仅能一个线程操作资源
     */
    public void put(String key,Object vla) throws InterruptedException {

        try {
            writeLock.lock();
            System.out.println(Thread.currentThread().getName()+"正在写入"+key);
            //暂停一会
            TimeUnit.SECONDS.sleep(1);
            map.put(key, vla);
            System.out.println(Thread.currentThread().getName()+"完成写入"+key);
        }catch (Exception exception){

        }finally {
            writeLock.unlock();
        }
    }

    public void get(String key) throws InterruptedException {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            //暂停一会
            TimeUnit.SECONDS.sleep(1);
            Object result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读取"+result);
        }catch (Exception exception){

        }finally {
            readLock.unlock();
        }
    }

}
